package com.umakr.ax.scheduler;

import com.umakr.ax.core.ModuleInit;
import com.umakr.ax.core.support.scheduler.ano.QuartzScheduler;
import com.google.common.collect.Lists;
import org.quartz.Scheduler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.Map;

/**
 * @author gx
 * @since 2017/6/1
 */
@Configuration
public class SchedulerConfig implements ModuleInit {

    @Bean
    @ConditionalOnMissingBean(SchedulerFactoryBean.class)
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext");
        schedulerFactoryBean.setSchedulerName("WFC-Scheduler");
        return schedulerFactoryBean;
    }

    @Bean
    public SchedulerService schedulerService(){
        return new SchedulerService();
    }
    @Bean
    public JobListener jobListener(){
        return new JobListener();
    }
    @Bean
    public SchedulerManager schedulerManager(Scheduler scheduler,JobListener jobListener){
        SchedulerManager schedulerManager = new SchedulerManager();
        schedulerManager.setJobListeners(Lists.newArrayList(jobListener));
        schedulerManager.setScheduler(scheduler);
        return schedulerManager;
    }
    @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
    private static void initQuartz(ApplicationContext rootAppContext){
        SchedulerService schedulerService  = rootAppContext.getBean(SchedulerService.class);
        for(Map.Entry<String,Object> entry : rootAppContext.getBeansWithAnnotation(QuartzScheduler.class).entrySet()){
            Object obj = entry.getValue();
            QuartzScheduler quartzScheduler = obj.getClass().getAnnotation(QuartzScheduler.class);
            TaskScheduled scheduled = new TaskScheduled();

            scheduled.setJobType("job");
            scheduled.setTaskType("LOCAL");
            scheduled.setTargetMethod(quartzScheduler.targetMethod());
            scheduled.setTargetObject(entry.getKey());
            scheduled.setTaskCron(quartzScheduler.trigger());
            scheduled.setTaskDesc(quartzScheduler.description());

            schedulerService.updateTask(scheduled);
        }

    }
    @Override
    public void moduleInit(ApplicationContext rootAppContext) {
        //初始化任务
        initQuartz(rootAppContext);
    }
}
